<template>
  <div class="app-container">
    <es-header title="购物车"></es-header>
    <es-goods v-for="item in goodslist" :key="item.id" :id="item.id" :goodstatus="item.goods_state" :count="item.goods_count" :imgsrc="item.goods_img" :goodsname="item.goods_name" :price="item.goods_price" @onCheckChange="getCheckStatus" @numberChange="getNum">
    </es-goods>
    <es-footer :amount="totalPrice" :total="totalNumber" @fullchange="getFullCheck"></es-footer>
  </div>
</template>

<script>
import EsHeader from './components/es-header/EsHeader.vue';
import EsFooter from './components/es-footer/EsFooter.vue';
import EsGoods from './components/es-goods/EsGoods.vue';
export default {
  name: 'MyApp',
  data() {
    return {
      //商品列表数据
      goodslist: []
    };
  },
  created() {
    this.getGoodsList();
  },
  methods: {
    // 获取商品列表数据
    async getGoodsList() {
      const { data: res } = await this.$http.get('/api/cart');
      if (res.status !== 200) return alert('请求失败');
      this.goodslist = res.list;
    },
    // 获取全选按钮状态
    getFullCheck(isfull) {
      // console.log(isfull);
      this.goodslist.forEach(x => (x.goods_state = isfull));
    },
    // 获取esgoods组件传递的状态和id值
    getCheckStatus(e) {
      // console.log('status' + e.id + ' - ' + e.state);
      const findResult = this.goodslist.find(x => x.id == e.id);
      if (findResult) {
        findResult.goods_state = e.state;
      }
    },
    // 处理子组件传递的 商品数量
    getNum(i) {
      // console.log(i.id + '-' + i.value);
      const findRes = this.goodslist.find(x => x.id == i.id);
      if (findRes) {
        findRes.goods_count = i.value;
      }
    }
  },
  components: {
    EsHeader,
    EsFooter,
    EsGoods
  },
  computed: {
    // 已勾选商品总价格
    totalPrice() {
      let total = 0;
      this.goodslist
        .filter(x => x.goods_state)
        .forEach(x => {
          total += x.goods_price * x.goods_count;
        });
      return total;
    },
    // 勾选商品数量
    totalNumber() {
      let num = 0;
      this.goodslist
        .filter(x => x.goods_state)
        .forEach(x => {
          num += x.goods_count;
        });
      return num;
    }
  }
};
</script>

<style scoped>
.app-container {
  padding-top: 45px;
  padding-bottom: 50px;
}
</style>